package org.xtext.runtime.interpreter;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class FileProfiler implements Profiler {
	PrintWriter writer;
	static PrintWriter cumWriter;
	String name;
	static Map<Long, Map<String, Long>> records = new HashMap<Long, Map<String, Long>>();
	static List<String> names = new LinkedList<String>();
	static boolean headersWritten = false;
	long start = -1;
	
	public static void recordCumulative(long iteration, String name, long sum) {
		Map<String,Long> map = records.get(iteration);
		if (map == null) {
			map = new HashMap<String,Long>();
			records.put(iteration, map);
		}
	
		if (iteration == 0) names.add(name);
		map.put(name, sum);
		
		if (map.size() == 20) {
			if (!headersWritten) {
				headersWritten=true;
				cumWriter.print("Iteration");
				for (String n : names) {
					cumWriter.print(","+ n);
				}
				cumWriter.println();
				cumWriter.flush();
			}
			
			
			cumWriter.print(iteration);
			for (String n : names) {
				cumWriter.print(","+ map.get(n));
			}
			cumWriter.println();
			cumWriter.flush();
		}
	}
	
	public FileProfiler(String name) {
		this.name = name;
		File file = new File("logs");
		if (!file.exists()) file.mkdir();
		
		try {
			writer = new PrintWriter(new FileWriter("logs/"+name + ".csv"));
			if (cumWriter == null) {
				cumWriter = new PrintWriter(new FileWriter("logs/cumulative.csv"));
//				cumWriter.println("Iteration,Agent,Total");
			}
			writer.println("Iteration,Start Time,Notifications,Updating,Sensing,Handle Event,Handle Intentions,DB Sizes,TR,Total");
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Override
	public void recordTimings(long iteration, long startTime, long[] timings, int events, int beliefs, int intentions, List<String> activities) {
		writer.print(iteration);
		if (start == -1) start= startTime;
		writer.print("," + (startTime-start));
		long sum = 0;
		for (int i=0;i<timings.length;i++) {
			sum += timings[i];
			writer.print("," + timings[i]);
		}
		writer.print(","+sum);
		writer.print(","+events + " ; " + beliefs +  " ; " + intentions);
		for (String activity : activities) {
			writer.print(",\"" + activity.replaceAll("\"", "\"\"")+"\"");
		}
		writer.println();
		writer.flush();
		writer.flush();
		recordCumulative(iteration, name, sum);
//		cumWriter.println(iteration+","+name+","+sum);
//		cumWriter.flush();
	}
}
